#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QFile>
#include <QDir>
#include <QFileDialog>
#include "QMessageBox"
#include <QDebug>
#include <QRegExp>
#include <QDate>
#include <QTime>
#include "QStandardPaths"


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    QString initcodecol,initpartcol;
    ui->setupUi(this);
    setWindowIcon(QIcon(":/new/prefix1/img/icon.png"));
    work_sheet=nullptr;
    work_books=nullptr;
    excel=nullptr;
    ui->name->setText("未添加文件");

    if(ReadInit("CodeCol", initcodecol))
        ui->codecomboBox->setCurrentText(initcodecol);

    if(ReadInit("PartCol", initpartcol))
        ui->comboBox->setCurrentText(initpartcol);
}

MainWindow::~MainWindow()
{
    delete ui;
}
bool MainWindow::WriteInit(QString key, QString value)
{
    QString path =  QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + "/bomtool.ini";
    QDir dir;
    QFile temp_path(path);
    //如果文件路径不存在
    if(!dir.exists(path))
     {
       temp_path.open(QIODevice::WriteOnly);
       temp_path.close();
     }
    //创建配置文件操作对象
     QSettings *config = new QSettings(path, QSettings::IniFormat);
     config->beginGroup("bomconf");
    //将信息写入配置文件
    config->setValue(key, value);
    config->endGroup();
    delete config;
    return  true;

}
bool MainWindow::ReadInit(QString key, QString &value)
{
        value = QString("");
         QString path =  QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + "/bomtool.ini";
        if (path.isEmpty() || key.isEmpty())
         {
                return false;
         }
        //创建配置文件操作对象
        QSettings *config = new QSettings(path, QSettings::IniFormat);

        //读取配置信息
        value = config->value(QString("bomconf/") + key).toString();
        delete config;
        return  true;
}
/*open bom*/
void MainWindow::on_pushButton_clicked()
{
      QString filepath = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
      QString fileName = QFileDialog::getOpenFileName(this, tr("选择工程文件"),
                                                      filepath,
                                                tr(("BOM Files(*.xls *.xlsx)")));
        if(fileName.isEmpty())
        {
            return;
        }
        excel = new QAxObject();
         if (!excel->setControl("Excel.Application"))//判断是否成功连接excel文件
         {
             delete excel;
             excel = NULL;
             QMessageBox::information(NULL, ("打开失败"), (""));
               return ;
         }
         excel->setProperty("Visible", false);
         work_books = excel->querySubObject("WorkBooks");
         work_books->dynamicCall("Open (const QString&)", fileName);
         if (work_books == NULL)
         {
             excel->dynamicCall("Quit(void)"); //退出
             delete excel;
             excel = NULL;
             QMessageBox::information(NULL, ("打开失败"), (""));
                return ;
         }
         QAxObject* work_book = excel->querySubObject("ActiveworkBook");
         if (work_book == NULL)
         {
             work_books->dynamicCall("Close(Boolean)", false); //关闭文件
             excel->dynamicCall("Quit(void)"); //退出
             delete work_books;
             work_books = NULL;
             delete excel;
             excel = NULL;
             QMessageBox::information(NULL, ("打开失败"), (""));
              return ;
         }

         work_sheet = work_book->querySubObject("Sheets(int)", 1);
         QAxObject *used_range = work_sheet->querySubObject("UsedRange");
         QAxObject *rows = used_range->querySubObject("Rows");
         QAxObject *columns = used_range->querySubObject("Columns");
        // int row_count = rows->property("Count").toInt();  //获取行数
        // int col_count = columns->property("Count").toInt();  //获取列数
         int row_count = 500;  //获取行数
         int col_count = 20;  //获取列数

      #if 1
         int startrowblag = 0;
         for (int i = 0; i < row_count; i++)
         {
             int rowemptycount = 0;

             for (int j = 0; j < col_count; j++)
             {
                 QString Text = work_sheet->querySubObject("Cells(int,int)",i+1,j+1)->dynamicCall("Value").toString();
                 if(Text.isEmpty())
                 {
                     rowemptycount++;
                 }
                 else
                 {

                     bool isDigital=Text.contains(QRegExp("^\\d+$"));
                     if((isDigital) && (j!=0) && (Text.length() <= 4))
                     {

                         if((startrowblag == 0) && ( numcol != j))
                         {
                             numcol = j;
                             startrow = i+1;
                             startrowblag = 1;
                         }
                        break;
                     }

                 }
             }
             if(rowemptycount == col_count)
             {
                  endrow = i;
                  ui->endrowspinBox->setValue(endrow);
                  ui->startspinBox->setValue(startrow);
                  ui->numcomboBox->setCurrentIndex(numcol);
                  break;
             }
         }
      #endif

       ui->textEdit->clear();
       ui->textEdit->append("打开文件成功");
       ui->name->setText(fileName);

}
/*编码重复检查*/
void MainWindow::on_pushButton_2_clicked()
{
     QStringList alltext;
     startrow=ui->startspinBox->value();
     endrow=ui->endrowspinBox->value();
     int col=ui->codecomboBox->currentIndex()+1;
    if(work_sheet==nullptr)
    {
      QMessageBox::information(NULL, ("文件没有打开"), (""));
      return;
    }
    for(int i=startrow;i<=endrow;i++)
    {
          QString Text = work_sheet->querySubObject("Cells(int,int)",i,col)->dynamicCall("Value").toString();
          alltext.append(Text);
    }
    for(int i=0;i<alltext.size();i++)
    {
       for(int j=0;j<alltext.size();j++)
       {
          if(i != j && alltext.at(i)==alltext.at(j))
          {
              QString ret="相同项为%1,%2:\" %3\"";
                 ui->textEdit->setTextColor(Qt::red);
              ui->textEdit->append( ret.arg(i).arg(j).arg(alltext.at(i)));
          }
       }
    }
     ui->textEdit->setTextColor(Qt::black);
     ui->textEdit->append("编码重复检查完成");
     WriteInit("CodeCol", ui->codecomboBox->currentText());
}

/*元器件位号重复检查*/
void MainWindow::on_pushButton_5_clicked()
{
   QStringList alltext;
   QStringList alltext1;
   startrow=ui->startspinBox->value();
   endrow=ui->endrowspinBox->value();

   int col=ui->comboBox->currentIndex()+1;

   if(work_sheet==nullptr)
   {
     QMessageBox::information(NULL, ("文件没有打开"), (""));
     return;
   }
   if(col==0)
   {
      QMessageBox::information(NULL, ("没有设置位号的列号"), (""));
      return;
   }
   for(int i=startrow;i<=endrow;i++)
   {
         QString Text = work_sheet->querySubObject("Cells(int,int)",i,col)->dynamicCall("Value").toString();
         qDebug()<<Text.simplified().toUpper();
         if(Text.size()>0)
         {
             alltext1.append(Text.simplified().toUpper());
             alltext.append(Text.simplified().toUpper().split(QRegExp(",|，|、|\\s+"),QString::SkipEmptyParts));
         }
   }
   for(int i=0;i<alltext.size();i++)
   {
      for(int j=0;j<alltext.size();j++)
      {
         if(i != j && alltext.at(i)==alltext.at(j))
         {
             QString ret="元器件重复为";
             QString code=alltext.at(i);
             QString doublecol="";
             ret=ret+code+":";
             for(int z=0;z<alltext1.size();z++)
             {
                 if(alltext1.at(z).indexOf(code)>=0)
                 {
                     doublecol.append(QString::number(z+startrow)+",");
                 }
             }
              ui->textEdit->setTextColor(Qt::red);
             ui->textEdit->append(ret+doublecol);
         }
      }
   }

  ui->textEdit->setTextColor(Qt::black);
  ui->textEdit->append("元器件位号重复检查完成");
  WriteInit("PartCol", ui->comboBox->currentText());
}
void MainWindow::on_pushButton_4_clicked()
{
    ui->textEdit->clear();
}

/*元器件数量检查*/
void MainWindow::on_pushButton_3_clicked()
{

    startrow=ui->startspinBox->value();
    endrow=ui->endrowspinBox->value();
    int codecol=ui->comboBox->currentIndex()+1;
    int numcol=ui->numcomboBox->currentIndex()+1;
    if(work_sheet==nullptr)
    {
      QMessageBox::information(NULL, ("文件没有打开"), (""));
      return;
    }
    if(codecol==0)
    {
       QMessageBox::information(NULL, ("没有设置位号的列号"), (""));
       return;
    }
    if(numcol==0)
    {
       QMessageBox::information(NULL, ("没有设置用量的列号"), (""));
       return;
    }
    QString ret="没有设置数量:%1";
    QString ret1="数量错误:%1";
    QString ret2="位号是空:%1";
    for(int i=startrow;i<=endrow;i++)
    {
          QString Text = work_sheet->querySubObject("Cells(int,int)",i,codecol)->dynamicCall("Value").toString();
          QString numText = work_sheet->querySubObject("Cells(int,int)",i,numcol)->dynamicCall("Value").toString();
              int num=numText.toInt();
              QStringList testlist = Text.simplified().split(QRegExp(",|，|、|\\s+"),QString::SkipEmptyParts);
               qDebug()<<testlist;
              if(num==0)
              {
                   ui->textEdit->setTextColor(Qt::red);
                   ui->textEdit->append(ret.arg(i));
              }
              else if (testlist.length()==0)
              {
                   ui->textEdit->setTextColor(Qt::red);
                   ui->textEdit->append(ret2.arg(i));
              }
             else  if(testlist.length()!=num)
              {
                   ui->textEdit->setTextColor(Qt::red);
                   ui->textEdit->append(ret1.arg(i));
              }
    }
    ui->textEdit->setTextColor(Qt::black);
    ui->textEdit->append("数量检查完成");
    WriteInit("PartCol", ui->comboBox->currentText());
}

void MainWindow::on_pushButton_6_clicked()
{
     work_books->dynamicCall("Close(Boolean)", false);
     excel->dynamicCall("Quit(void)"); //退出
      delete work_books;
      delete excel;
     work_sheet=nullptr;
     work_books=nullptr;
     excel=nullptr;
     ui->name->setText("未添加文件");
     ui->textEdit->append("关闭文件");
}
/*全面检查*/
void MainWindow::on_pushButton_7_clicked()
{
      on_pushButton_3_clicked();
      on_pushButton_5_clicked();
      on_pushButton_2_clicked();
}
